﻿using MKAdmin.DTO.Web.Common;
using MKAdmin.DTO.Web.Excel.Import;
using MKAdmin.IService.Web.Excel;
using MKAdmin.ToolKit;
using MKAdmin.ToolKit.FileKit;
using MKAdmin.Web.App_Start;
using MKAdmin.Web.Authorizes;
using MKAdmin.Web.Controllers;
using Ninject;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MKAdmin.Web.Areas.Excel.Controllers
{
    public class ImportController : BaseMvcController
    {
        [Inject]
        public IImportService ImportService { set; get; }

        // GET: Excel/Import
        public ActionResult Index()
        {
            return View(PageViewFilesConfig.ExcelImportIndex);
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <returns></returns>
        public JsonResult ImportData(ImportDataParameter parameter)
        {
            var result = new Result();
            FileHelper.CopyFile("Excel", parameter.catalog, parameter.fileName);
            var catalogConfig = FileCatalogHelper.Catalog["Excel"];
            string filePath = $@"{catalogConfig.DestFile.AbsolutePath}/{parameter.catalog.Replace("/", "\\")}\{parameter.fileName}";

            DataTable dtResult = ExcelHelper.ImportToDataTable(new ExcelConvertToDataParamater()
            {
                fileName = filePath
            });
            if (dtResult != null && dtResult.Rows.Count > 0)
            {
                if (dtResult.Columns.Count == 6)
                {
                    var userInfo = CurrentUser.GetLoginInfo();

                    result = ImportService.ImportData(dtResult, userInfo);
                }
                else
                {
                    result.status = false;
                    result.msg = "导入文件格式有误!";
                }
            }
            else
            {
                result.status = false;
                result.msg = "导入文件中未检测到数据!";
            }

            return Json(result, JsonRequestBehavior.DenyGet);
        }
    }
}